using System;

namespace Tycho.Parser.Peg {
    public class NamedRule : Rule {
        public string Name;

        public NamedRule (string name, IProduction production) {
            Name = name;
            Production = production;
        }

        public override bool HasProduction {
            get {
                return true;
            }
        }

        public override IProduction Production { get; set; }

        public override Yield Parse (char[] source, int index, ParseContext context, string sourceString, ParseEnvironment environment, Func<RuleParseResult, Yield> continuation) {
            return Production.Parse (source, index, context, sourceString, environment, result => {
                if (result != null) {
                    var ruleResult = new RuleParseResult (result.Index, result.Context);
                    ruleResult.AddCapture (Name, result.Term);
                    return () => continuation (ruleResult);
                } else {
                    return () => continuation (null);
                }
            });
        }
    }
}